from flask import Blueprint, request, jsonify
from app import db, jwt
from app.models.health_assessment import HealthAssessment
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

bp = Blueprint('health_assessment', __name__, url_prefix='/api/health-assessment')

@bp.route('', methods=['POST'])
@jwt_required()
def create_health_assessment():
    """创建健康评估记录"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # 处理日期字段 - 将字符串转换为datetime对象
        next_checkup_date_str = data.get('next_checkup_date')
        next_checkup_date = None
        if next_checkup_date_str:
            try:
                next_checkup_date = datetime.strptime(next_checkup_date_str, '%Y-%m-%d')
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        health_assessment = HealthAssessment(
            user_id=user_id,
            overall_health_score=data.get('overall_health_score'),
            health_risk_level=data.get('health_risk_level'),
            bmi_category=data.get('bmi_category'),
            cardiovascular_risk=data.get('cardiovascular_risk'),
            diabetes_risk=data.get('diabetes_risk'),
            metabolic_risk=data.get('metabolic_risk'),
            recommendations=data.get('recommendations'),
            next_checkup_date=next_checkup_date
        )
        
        db.session.add(health_assessment)
        db.session.commit()
        
        return jsonify({
            'message': '健康评估记录创建成功',
            'data': health_assessment.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('', methods=['GET'])
@jwt_required()
def get_health_assessments():
    """获取用户的全部健康评估记录"""
    try:
        user_id = get_jwt_identity()
        records = HealthAssessment.query.filter_by(user_id=user_id).order_by(HealthAssessment.assessment_date.desc()).all()
        
        return jsonify({
            'data': [record.to_dict() for record in records]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['GET'])
@jwt_required()
def get_health_assessment_by_id(record_id):
    """获取特定健康评估记录"""
    try:
        user_id = get_jwt_identity()
        record = HealthAssessment.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
            
        return jsonify({
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
def update_health_assessment(record_id):
    """更新健康评估记录"""
    try:
        user_id = get_jwt_identity()
        record = HealthAssessment.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        data = request.get_json()
        
        # 处理日期字段
        if 'next_checkup_date' in data and data['next_checkup_date']:
            try:
                record.next_checkup_date = datetime.strptime(data['next_checkup_date'], '%Y-%m-%d')
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        # 更新其他字段
        update_fields = [
            'overall_health_score', 'health_risk_level', 'bmi_category',
            'cardiovascular_risk', 'diabetes_risk', 'metabolic_risk',
            'recommendations'
        ]
        
        for field in update_fields:
            if field in data:
                setattr(record, field, data[field])
        
        db.session.commit()
        
        return jsonify({
            'message': '健康评估记录更新成功',
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['DELETE'])
@jwt_required()
def delete_health_assessment(record_id):
    """删除健康评估记录"""
    try:
        user_id = get_jwt_identity()
        record = HealthAssessment.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        db.session.delete(record)
        db.session.commit()
        
        return jsonify({
            'message': '健康评估记录删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/latest', methods=['GET'])
@jwt_required()
def get_latest_health_assessment():
    """获取最新的健康评估记录"""
    try:
        user_id = get_jwt_identity()
        record = HealthAssessment.query.filter_by(user_id=user_id).order_by(HealthAssessment.assessment_date.desc()).first()
        
        if not record:
            return jsonify({'error': '暂无健康评估记录'}), 404
            
        return jsonify({
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500